
#include <SdFat.h>
#include <SdFatUtil.h>
#include "TimerOne.h"

// number of blocks in the contiguous file
//#define BLOCK_COUNT 6*1600*2*60*1/512UL
#define BLOCK_COUNT 22500UL

Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

uint32_t bgnBlock, endBlock,b;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))

void error_P(const char* str) {
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup(void) {
  Serial.begin(9600);
 Timer1.initialize(625);         // initialize timer1, and set a 1/2 second period
 Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void loop(void) {
  Serial.flush();
  PgmPrintln("Type any character to start");
  while (!Serial.available());

  // initialize the SD card
  uint32_t t = millis();
  
  // initialize the SD card at SPI_FULL_SPEED for best performance.
  // try SPI_HALF_SPEED if bus errors occur.
  if (!card.init(SPI_FULL_SPEED)) error("card.init failed");
  
  t = millis() - t;
  
  PgmPrint("Card init time: ");
  Serial.print(t);
  PgmPrintln(" millis");
  
  // initialize a FAT volume
  if (!volume.init(&card)) error("volume.init failed");
  
  // open the root directory
  if (!root.openRoot(&volume)) error("openRoot failed");
  
  // delete possible existing file
  SdFile::remove(&root, "RAW.TXT");
  
  // create a contiguous file
  if (!file.createContiguous(&root, "RAW.TXT", 512UL*BLOCK_COUNT)) {
    error("createContiguous failed");
  }
  // get the location of the file's blocks
  if (!file.contiguousRange(&bgnBlock, &endBlock)) {
    error("contiguousRange failed");
  }
  //*********************NOTE**************************************
  // NO SdFile calls are allowed while cache is used for raw writes
  //***************************************************************
  
  // clear the cache and use it as a 512 byte buffer
  uint8_t* pCache = volume.cacheClear();
  
  // fill cache with eight lines of 64 bytes each
  memset(pCache, ' ', 512);
  for (uint16_t i = 0; i < 512; i += 64) {
    // put line number at end of line then CR/LF
    pCache[i + 61] = '0' + (i/64);
    pCache[i + 62] = '\r';
    pCache[i + 63] = '\n';
  }
  
  PgmPrint("Start raw write of ");
  Serial.print(file.fileSize());
  PgmPrintln(" bytes");
  

  
  // tell card to setup for multiple block write with pre-erase
  if (!card.erase(bgnBlock, endBlock)) error("card.erase failed");
  if (!card.writeStart(bgnBlock, BLOCK_COUNT)) {
    error("writeStart failed");
  }
  t = millis();
  uint32_t tNext = t;

  // write data
  for (b = 0; b < BLOCK_COUNT; b++) {
    // write must be done by this time
    

//    // put block number at start of first line in block
//    uint32_t n = b;
//    for (int8_t d = 5; d >= 0; d--){
//      pCache[d] = n || d == 5 ? n % 10 + '0' : ' ';
//      n /= 10;
//    }
//    Serial.println(b);
    if (!card.writeData(pCache)) error("writeData failed");
   
  }
  // total write time
  t = millis() - t;
  
  // end multiple block write mode
  if (!card.writeStop()) error("writeStop failed");
  
  PgmPrintln("Done");
  
  PgmPrint("Elapsed time: ");
  Serial.print(t);
  PgmPrintln(" millis");
  
  // close files for next pass of loop
  root.close();
  file.close();
  Serial.println();
}
